######################### Load Libraries #######################################

library(seatsvotes)

library(lattice)

############################ Load Data #########################################

# set working directory to obtain seats-votes estimates
setwd("~/_data/sv_estimates")

# load seats-votes estimates for US
load("us.RData")

############################ Functions #########################################

# function to extract swing ratio matrix; here sw is the object with the swing ratio estimates (e.g., sr06) 
srmat <- function(sw) {

	swi <- vector("list",length(sw$swing))
		
		for (i in 1:length(swi)) {
		
			swi[[i]][[1]] <- sw$seatmat[(sw$votemat[, i] < (sw$truevote[i] + 
            0.012)) & (sw$votemat[, i] > (sw$truevote[i] + 0.008)), 
            i]
	
			swi[[i]][[2]] <- sw$seatmat[(sw$votemat[, i] > (sw$truevote[i] - 
            0.012)) & (sw$votemat[, i] < (sw$truevote[i] - 0.008)), 
            i]
            
            names(swi[[i]])[[1]] <- paste("s.hi", names(sw$swing)[i], sep=".")
            
            names(swi[[i]])[[2]] <- paste("s.lo", names(sw$swing)[i], sep=".")

		}
		
		swi

}


# function to generate bootstraps; here srm is the object resulting from applying the function srmat (e.g., sw06), m is the number of bootstraps, n is the sample size used for each bootstrap, j is the index for the swing ratio estimates (e.g., in the example 1 refers to Republicans)
srboot <- function(srm,m,n,j) {

	boot <- vector("list",m)

		for (i in 1:m) {
	
			boot[[i]] <- ( sample(srm[[j]][[1]], n, replace = TRUE) - sample(srm[[j]][[2]], n, replace = TRUE) )/0.02
			
		}
		
	boot
	
}

############################# Bootstrap ########################################

# set random number seed for replicability
set.seed(1234)

# apply srmat function to 2006 US data
sw06 <- srmat(sr06)

# generate bootstrapped seats-votes estimates
boot06.dem <- srboot(sw06,1000,100,3)

# convert bootstrapped seats-votes estimates to vector
boot06.dem.est <- unlist(lapply(boot06.dem,median))

########################## Load/Prep US LPR Data ###############################

# set working directory
setwd("~/_data")

# load LPR data
load("lprdata_plus.RData")

# generate separate matrix for US
usa <- all[all$country=="USA",]

# generate empty list to store seat swings from bootstraps
s <- vector("list",length(boot06.dem.est))

# generate seat swing estimates
for (i in 1:length(boot06.dem.est)) {

	s[[i]] <- rep(NA,30)
	
		for (j in 1:30) {
	
			s[[i]][j] <- usa$DParty1[j]*boot06.dem.est[i] - usa$DParty2[j]*usa$tau.Party2[31]
	
		}

}

# empty vector for bootstrapped LPR
lossprob.boot <- rep(NA,length(s))

# calculate LPR
for (i in 1:length(s)) {
	
	z.smd <- density(s[[i]][is.na(s[[i]])==F])
	f.smd <- approxfun(z.smd$x, z.smd$y, yleft = 0, yright = 0)
	lossprob.boot[i] <- integrate(f.smd, -Inf, -usa$seatsharegap[31])$value

}

################################## SM Figure 6 #################################

# set working directory for SM graphs
setwd("~/_supportingmaterials_tabfig/")

# generate final pdf graph
pdf("boot_tau.pdf")

densityplot(lossprob.boot,bw=0.005,,xlab="LPR Based on Bootstrapped S-V Elasticities (Democrats, 2006)",par.settings = list(plot.symbol = list(col = "black"),plot.line = list(col = "black")),
	panel=function(x, ...){
     panel.densityplot(x, ...)
     panel.abline(v=usa$lossprob_statictau[31],lty=2)
   })
   
dev.off()